/*
 * @Author: Zhang Kai
 * @Date: 2021-11-10 20:39:01
 * @LastEditors: mayijun
 * @LastEditTime: 2022-08-10 11:06:16
 * @FilePath: /metricsx-standard-ui/src/components/Arithmetic/index.tsx
 */
import { defineComponent, onMounted, ref, watch, watchEffect } from 'vue';
import SymbolPopover from '@/components/Arithmetic/components/SymbolPopover';
import { CaretBottom, RemoveFilled, Check } from '@element-plus/icons-vue';
import SelectIndex from './components/SelectIndex';
import './index.scss';
import API from '@/services';
import { EDicType } from '@/utils/constants';
const Arithmetic = defineComponent({
  name: 'Arithmetic',
  components: { CaretBottom, RemoveFilled, Check },
  props: {
    /* 指标列表API类型 */
    metricsType: {
      type: String,
      default: 'DERIVED'
    },
    subjectId: {
      type: String,
      default: ''
    },
    addCurrentIndex: {
      type: Object,
      default: () => { }
    },
    editData: {
      type: Object,
      default: () => { }
    },
    arithmeticItem: {
      type: Object,
      default: () => { }
    },
    isSubject: {
      type: Boolean,
      default: true
    },
    list: {
      type: Array,
      default: () => []
    },
    /* 是否需要远程搜索 */
    isRemote: {
      type: Boolean,
      default: true
    },
    subType: {
      type: Number,
      default: 0
    },
    isOnlyIndex: {
      type: Boolean,
      default: false
    },
    //使用类型，0，指标定义，1，自助取数
    useType: {
      type: Number,
      default: 0
    },
  },
  emits: ['changeIndex', 'del'],
  setup: (props, { slots, attrs, emit }) => {
    /* 聚合方式list */
    const CombineEnumList = ref();

    /* 当前聚合方式 */
    const CombineEnumItem = ref();

    /* 聚合方式框visible */
    const popoverVisible = ref(false);

    /* 弹出框visible */
    const dialogVisible = ref(false);

    /* 当前选中的指标 */
    const selectIndexItem = ref();

    /* 数字input */
    const numInput = ref('');

    const beforeSymbol = ref('');

    const afterSymbol = ref('');

    const subjectIds = ref('');

    /* 指标运算逻辑聚合方式 */
    const getCombineEnum = async () => {
      try {
        let res: any = {};
        if (props.useType == 0) {
          res = await API.atomicMetrics.getAtomicMetricsCombineEnum();
        } else {
          res = await API.dictionaryConfig.getDictionaryConfigEnumTypeByEnumType({
            enumType: EDicType.aggregation
          });
        }
        if (res.code === 200 && Array.isArray(res.data)) {
          CombineEnumList.value = res.data;
        }
      } catch (error) {
        console.log(error);
      }
    };

    const getQuery = () => {
      return {
        beforeSymbol: beforeSymbol.value,
        afterSymbol: afterSymbol.value,
        numInput: numInput.value,
        CombineEnumVal: CombineEnumItem.value.value,
        CombineEnumName: CombineEnumItem.value.label,
        selectIndexId: selectIndexItem.value.id,
        selectIndexName: selectIndexItem.value.label,
        subjectId: subjectIds.value,
        businessMeaning: selectIndexItem.value.businessMeaning,
        subType: selectIndexItem.value.subType
      };
    };

    watchEffect(() => {
      if (!Object.keys(props?.arithmeticItem).length) return;
      beforeSymbol.value = props.arithmeticItem.beforeSymbol;
      afterSymbol.value = props.arithmeticItem.afterSymbol;
      let value = props.useType == 0 ? 'SUM' : "66"
      CombineEnumItem.value = {
        label: props.arithmeticItem.CombineEnumName || '求和',
        value: props.arithmeticItem.CombineEnumVal || value
      };
      selectIndexItem.value = {
        label: props.arithmeticItem.selectIndexName,
        id: props.arithmeticItem.selectIndexId
      };
      numInput.value = props.arithmeticItem.numInput;
      subjectIds.value = props?.subjectId;
    });

    onMounted(() => {
      getCombineEnum();
      if (props.useType == 1) {
        CombineEnumItem.value.value == "66";
        CombineEnumItem.value.value == "求和";
      }else{
        CombineEnumItem.value.value == "SUM";
        CombineEnumItem.value.value == "求和";
      }
    });
    return () => {
      const {
        addCurrentIndex,
        isSubject,
        list,
        metricsType,
        isRemote,
        subType,
        isOnlyIndex
      } = props;
      return (
        <div class="Arithmetic">
          <SymbolPopover
            symbolVal={beforeSymbol.value}
            onSymbolClick={(v) => {
              beforeSymbol.value = v;
              emit('changeIndex', getQuery());
            }}
          />
          <div class="ArithmeticSelect">
            <el-tooltip
              effect="dark"
              content={selectIndexItem?.value?.label || addCurrentIndex}
              placement="top"
            >
              {/* 指标展示 */}
              <div
                onClick={() => (dialogVisible.value = true)}
                class="ArithmeticSelect-index"
              >
                {selectIndexItem?.value?.label || addCurrentIndex}
              </div>
            </el-tooltip>

            {/* 指标选择 */}
            <SelectIndex
              subType={subType}
              isRemote={isRemote}
              metricsType={metricsType}
              list={list}
              isSubject={isSubject}
              indexItem={selectIndexItem.value}
              subjectId={subjectIds.value}
              isOnlyIndex={isOnlyIndex}
              onIndexChange={(v: any, subjectId) => {
                selectIndexItem.value = v;
                subjectIds.value = subjectId;
                emit('changeIndex', getQuery());
              }}
              v-model={[dialogVisible.value, 'dialogVisible']}
            />

            {/* 指标运算逻辑聚合方式框 */}
            <el-popover
              visible={popoverVisible.value}
              placement="bottom"
              width="200"
              trigger="click"
              v-slots={{
                reference: () => (
                  <div
                    onClick={() =>
                      (popoverVisible.value = !popoverVisible.value)
                    }
                    class="CombineEnum-inner"
                  >
                    {CombineEnumItem.value.label}
                    <el-icon color="#999999">
                      <CaretBottom />
                    </el-icon>
                  </div>
                )
              }}
            >
              <div class="CombineEnumList">
                {CombineEnumList?.value?.map((v: any) => (
                  <div
                    class={[
                      'CombineEnumList-item',
                      { active: CombineEnumItem.value.value === v.value }
                    ]}
                    onClick={() => {
                      CombineEnumItem.value = v;
                      popoverVisible.value = false;
                      emit('changeIndex', getQuery());
                    }}
                  >
                    <div>{v.label}</div>
                    {CombineEnumItem.value.value === v.value && (
                      <el-icon color="#4273F5">
                        <Check />
                      </el-icon>
                    )}
                  </div>
                ))}
              </div>
            </el-popover>

            {/* 删除 */}
            <span class="icon-wrap">
              <el-icon onClick={() => emit('del')} color="#ff1a3b">
                <RemoveFilled />
              </el-icon>
            </span>
          </div>

          <SymbolPopover
            symbolVal={afterSymbol.value}
            onSymbolClick={(v) => {
              afterSymbol.value = v;
              emit('changeIndex', getQuery());
            }}
          />
          <div class="numInput">
            <span>{numInput.value}</span>
            <input
              onChange={() => emit('changeIndex', getQuery())}
              v-model={numInput.value}
              type="text"
            />
          </div>
        </div>
      );
    };
  }
});
export default Arithmetic;
